#!/bin/bash

# This script will go through each of the modules and verify that each string key is
# associated with android in localize.  If it isn't the script will search for the string
# value in the localize android and ios project.
#
# This script requires that localize.sh is run first, if it is not it will exit with an error.
#
# This script can be run with no arguments:
#  ./untranslated_project_key.sh

if [ -z "$API_TOKEN" ]; then
  echo "You need to add the API_TOKEN to: localization_vars.sh"
  exit
fi

if [[ -z $(which lokalise2) ]]; then
    echo "Installing lokalise2 via homebrew..."
    brew tap lokalise/cli-2
    brew install lokalise2
fi

if [[ -z $(which recode) ]]; then
    echo "Installing recode via homebrew..."
    brew install recode
fi

source localization_vars.sh

# This is the custom status ID for our project with which the localizers mark completed translations
FINAL_STATUS_ID=587

for MODULE in ${MODULES[@]}
do
   if [ ! -f  "android/$MODULE-lokalize-strings.xml" ]; then
      echo "You must run localize.sh first"
      exit 1
   fi

   # List all the strings / android/$MODULE-strings.xml is generated by the localize.sh script
   cat android/$MODULE-lokalize-strings.xml | gsed -E -n "s/\s*<string name=\"(.*)\">.*<\/string>/\1/pI" > android/$MODULE-localize_android_keys.txt
   sort -o android/$MODULE-localize_android_keys-sorted.txt android/$MODULE-localize_android_keys.txt

   # List all the keys in the android project.
   cat ../$MODULE/res/values/strings.xml | gsed -E -n "s/\s*<string name=\"([^ ]*)\".*>(.*)<\/string>/\1/pI" > android/$MODULE-project_keys.txt
   sort -o android/$MODULE-project_keys-sorted.txt android/$MODULE-project_keys.txt

   diff -u android/$MODULE-localize_android_keys-sorted.txt android/$MODULE-project_keys-sorted.txt  | grep -E "^[\+][a-z]" | sed 's/^+//g' > android/diff_keys-$MODULE.txt

   echo ""
   echo ""
   echo $MODULE has untranslated keys:
   echo "-----------------------"
   cat android/diff_keys-$MODULE.txt

   echo ""
   echo "Finding strings in localize with the same string value"

   # Find the
   cat ../paymentsheet/res/values/strings.xml | grep -f android/diff_keys-paymentsheet.txt  | \
       gsed -E -n "s/\s*<string name=\"(.*)\">(.*)<\/string>/\2/pI" | \
       while IFS= read -r line ; do
          ./find_localize_key_for_value_regex.sh "${line}" ;
       done

   rm android/$MODULE-project_keys-sorted.txt
   rm android/$MODULE-project_keys.txt
   rm android/$MODULE-localize_android_keys-sorted.txt
   rm android/$MODULE-localize_android_keys.txt

done

for MODULE in ${MODULES[@]}
do
  if [[ $(wc -l <android/diff_keys-$MODULE.txt) -ge 0 ]]; then
    echo "You must correct the strings with keys before proceeding."
    exit 2
  fi
done


